<!-- 包含组织树的 dynamic -->
<template>
  <div class="dynamic-container dynamic-org-container">
    <div v-show="!showMaster">
      <div class="dynamicBreadCrumb">
        <div style="float: left">
          <bread-crumb :child-data="selectedRow.funNo" class="card-bread-crumb"></bread-crumb>
        </div>
        <div style="float: right">
          <dynamicButton
            :permissionPrefix="permissionPrefix"
            :buttonData="dynamicData.buttonData"
            class="dynamicButton"
            @updateValue="passToMaster"
            @handleExport="exportExcel"
            @handleRemove="handleRemove"
          ></dynamicButton>
        </div>
      </div>
      <el-row :gutter="20" style="margin-left: 0px; margin-right: -10px; flex:auto">
        <el-col
          :span="4"
          :xs="24"
          class="is-always-shadow"
          v-if="hamgurgerActive"
          style="margin-left: 14px;"
        >
          <div class="head-container">
            <el-input
              v-model="deptName"
              placeholder="请输入组织名称"
              clearable
              size="small"
              prefix-icon="el-icon-search"
              style="margin:10px 0 20px 0"
            />
          </div>
          <div class="head-container" :style="{'height' : divTreeMinHeight}" v-if="hamgurgerActive">
            <el-tree
              node-key="id"
              :current-node-key="queryParams.ct_branch_level"
              :data="deptOptions"
              :props="defaultProps"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              ref="tree"
              :default-expand-all="false"
              :default-expanded-keys="[queryParams.ct_branch_level]"
              :highlight-current="true"
              @node-click="handleNodeClick"
              class="treeStyle"
              :style="{ overflow:'auto'}"
              :render-content="misRenderContent"
            ></el-tree>
          </div>
        </el-col>
        <div style="overflow: scroll;height:100%;">
          <el-col :span="24" :xs="24" class="flex-col">
            <el-card
              class="box-card dynamicSearch"
              style="padding:5px 0 5px 15px; marginBottom:10px"
            >
              <dynamicSearch
                :hamgurgerActive="hamgurgerActive"
                ref="dySearch"
                :searchData="dynamicData.searchData"
                @postForm="getList"
                @resetSearch="getRetrieve"
                @switchOrgTree="switchOrgTree"
                :isFloatRight="false"
              ></dynamicSearch>
            </el-card>
            <el-card class="box-card dynamicContext" ref="contextCard">
              <dynamicList
                ref="dyList"
                :viewData="dynamicData.viewData"
                :addFormData="dynamicData.addFormData"
                :queryParams="queryParams"
                @updateValue="passToMaster"
                @switchShowMaster="switchShowMaster"
                class="dynamicList"
                :permissionPrefix="permissionPrefix"
              ></dynamicList>
            </el-card>
          </el-col>
        </div>
      </el-row>

      <dynamicAddForm
        ref="addForm"
        :handleType="dynamicData.handleType"
        :updateData="dynamicData.updateData"
        :addFormData="dynamicData.addFormData"
        class="dynamicAddForm"
      ></dynamicAddForm>
    </div>
    <div class="dialogList" v-show="showMaster">
      <spsMaster ref="spsMaster" :queryParams="selectedRow" @back="switchShowMaster"></spsMaster>
    </div>
  </div>
</template>

<script>
import dynamicList from '@/components/SpsPublic/Dynamic/dynamicList'
import dynamicSearch from '@/components/SpsPublic/Dynamic/dynamicSearch'
import dynamicButton from '@/components/SpsPublic/Dynamic/dynamicButton'
import dynamicAddForm from '@/components/SpsPublic/Dynamic/dynamicAddForm'
import spsMaster from '@/components/SpsPublic/Master/SpsMaster'
import { baseListRetrieveCondition } from '@/api/mis/retrievecondition'
import { listMisView } from '@/components/SpsPublic/Dynamic/misView.js'
import { getBaseFunction } from '@/api/mis/function'
import BreadCrumb from '@/components/SpsPublic/BreadCrumb/BreadCrumb'
import store from '@/store/index'
import { getFunNo } from '@/utils/party'
import { permissionByFunNo } from '@/api/system/menu.js'
import { exportMisTableData } from '@/components/SpsPublic/Dynamic/tableData.js'
import { getTreeView } from '@/api/spsParty/treeView.js'
import Hamburger from '@/components/Hamburger'
import { misRenderContent } from '@/utils'
import cacheDestory from '@/utils/mixins/cacheDestory'

export default {
  name: 'OrgTreeDynamic',
  mixins: [cacheDestory],
  components: {
    dynamicList,
    dynamicSearch,
    dynamicButton,
    dynamicAddForm,
    spsMaster,
    BreadCrumb,
    Hamburger,
  },
  computed: {
    // tableHeight() {
    //   return store.state.dynamic.tableHeight
    // },
  },
  watch: {
    deptName(val) {
      this.$refs.tree.filter(val)
    },
  },
  data() {
    return {
      // 左侧组织树显示状态
      hamgurgerActive: true,
      hamgurgerSpan: 4,
      // routePath: '',
      permissionPrefix: 'dynamic:button:',
      store: store,
      timer: 0,
      dynamicData: {
        searchData: [],
        viewData: [],
        buttonData: {
          add: true,
          update: true,
          delete: true,
        },
        addFormData: {
          title: '',
          formData: [],
        },
        updateData: {},
        handleType: 'add',
        conType: {
          datePicker: 'el-date-picker',
          treeSelect: 'mis-select-tree',
        },
      },
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        ctFunNo: getFunNo(this.$route),
        queryType: this.$route.name.slice(-5).substring(0, 1),
        ct_branch_level: store.state.user.branchInfo.manageBranchLevel,
      },
      selectedRow: {
        selectedCt: null,
        funNo: getFunNo(this.$route),
        functionData: {},
      },
      showMaster: false,
      dateFormat: '{y}-{m}-{d}',
      divTreeMinHeight: document.documentElement.clientHeight - 239 + 'px',
      // 部门树选项
      deptOptions: [],
      defaultProps: {
        children: 'children',
        label: 'label',
      },
      // 部门名称
      deptName: undefined,
    }
  },
  created() {
    // 判断当前登录人管辖组织类型， 总部显示左侧树形结构， 分部则不显示
    if (store.state.user.branchInfo.ifPartyCommittee == '0') {
      this.hamgurgerActive = false
    }
    store.dispatch('createSingleStore', this.selectedRow.funNo)
    permissionByFunNo(this.queryParams.ctFunNo).then((response) => {
      if (response && response.code === 200) {
        this.permissionPrefix = response.data
      }
    })
    // 请求获取搜索查询信息数据
    this.getRetrieve()
    // 获取table展示列数据
    this.getMisView()
    // this.getTableheight()
    window.addEventListener('resize', () => {
      this.onResize()
    })
    this.getTreeselect()
  },

  methods: {
    misRenderContent,
    switchOrgTree() {
      this.hamgurgerActive = !this.hamgurgerActive
    },
    // 导出表格信息
    exportExcel() {
      const that = this
      this.$confirm('是否确认导出数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(function () {
          return exportMisTableData(that.queryParams)
        })
        .then((response) => {
          that.download(response.msg)
        })
    },
    // 获取该功能的数据
    getFunctionData() {
      const promise = new Promise((resolve, reject) => {
        getBaseFunction(this.queryParams.ctFunNo).then((response) => {
          this.selectedRow.functionData = response.data
          const pageSize = response.data.amRow
          if (pageSize && pageSize > 0 && pageSize <= 100) {
            this.queryParams.pageSize = pageSize
          }
          store.dispatch('setCtFun', this.selectedRow.functionData)
          resolve()
        })
      })
      const that = this
      promise.then(() => {
        that.$refs.dySearch.postForm()
      })
    },
    onResize() {
      this.timer && clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        // this.getTableheight()
        this.divTreeMinHeight =
          document.documentElement.clientHeight - 239 + 'px'
      }, 500)
    },
    // getTableheight() {
    //   this.$nextTick(function () {
    //     if (this.$refs.contextCard) {
    //       var tableHeight = document.documentElement.clientHeight - 345
    //       store.dispatch('setTabelHeight', tableHeight)
    //     }
    //   })
    // },
    // 传值至spsMaster
    passToMaster(value) {
      this.selectedRow.selectedCt = value
      this.switchShowMaster(false)
      this.$refs['spsMaster'].resetTabSelected()
      this.$refs['spsMaster'].refresh()
    },
    // 切换master显示
    switchShowMaster(refreshFlag) {
      // master中数据保存，则刷新列表
      if (refreshFlag) {
        this.$refs.dyList.getList()
      }
      this.showMaster =
        store.getters.singleStore['main' + this.selectedRow.funNo].showMaster
    },
    // 获取表格显示列
    getMisView() {
      this.loading = true
      listMisView(this.queryParams).then((response) => {
        this.dynamicData.viewData = response.rows
        this.dynamicData.viewData = this.dynamicData.viewData.filter(
          (column) => {
            return column.ctIfTable == '1'
          }
        )
        this.loading = false
      })
    },
    // 获取搜索查询信息数据
    getRetrieve() {
      baseListRetrieveCondition(this.queryParams).then((response) => {
        this.dynamicData.searchData = response.rows
        // 包含下级元素的位置
        let index = -1
        let checkValue = true
        for (let i = 0; i < this.dynamicData.searchData.length; i++) {
          const item = this.dynamicData.searchData[i]
          if (
            item.ctConType == this.dynamicData.conType.treeSelect &&
            item.ctConTreetype == '99' &&
            item.ctConDisp
          ) {
            checkValue = item.ctColDefaultv == '1'
            //   组织的下拉查询，赋登录人的管辖范围初始值
            item.ctColDefaultv = store.state.user.branchInfo.manageBranchLevel
            index = i + 1
          }
        }
        if (index != -1) {
          const retrieve = {
            ctConType: 'el-checkbox',
            ctColDefaultv: checkValue,
            ctColName: 'includeFlag',
            ctColTitle: '',
            ctConDisp: true,
          }
          this.dynamicData.searchData.splice(index, 0, retrieve)
        }
        // 获取该功能的数据
        this.getFunctionData()
      })
    },
    // 查询表格数据
    getList(val) {
      var keys = Object.keys(val)
      for (var i = 0; i < keys.length; i++) {
        this.queryParams[keys[i]] = val[keys[i]]
      }
      this.$refs['dyList'].getList()
    },
    // 删除操作
    handleRemove() {
      this.$refs.dyList.handleDelete()
    },

    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.ctLevelC,
        parentId: node.ctLevelP,
        label: node.ctName,
      }
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.ct_branch_level = data.id
      for (const iterator of this.dynamicData.searchData) {
        if (iterator.ctColName == 'ct_branch_level') {
          iterator.ctColDefaultv = data.id
        }
      }
      this.$refs.dyList.getList()
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      // 获取当前登录人管理的部门信息
      const me = this
      const param = 99
      getTreeView(param).then((response) => {
        let data = response.data
        let arr = []
        data.map((item) => {
          arr.push(me.normalizer(item))
        })
        this.deptOptions = this.handleTree(arr, 'id', 'parentId')
      })
    },
  },
}
</script>

<style scoped lang="scss">
.box-card {
  margin: 4px 10px 4px 10px;
}
.dynamicSearch {
  overflow: visible !important;
}

.card-bread-crumb {
  margin-left: 11px;
  margin-bottom: 3px;
}

// .dynamic-org-container .dynamicList {
//   position: relative;
//   height: auto !important;
// }
.flex-col {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  -ms-flex-direction: column;
  flex-direction: column;
  height: 100%;
}
.dynamic-org-container .is-always-shadow {
  -webkit-box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-top: 4px;
  border-radius: 4px;
  border: 1px solid #e6ebf5;
  background-color: #ffffff;
  overflow: hidden;
  color: #303133;
  -webkit-transition: 0.3s;
  transition: 0.3s;
  min-height: 64px;
}

.dynamic-org-container .head-container {
  overflow: auto;
}
.dynamic-org-container .el-col-1 {
  width: 2.5%;
}

.dynamic-org-container .treeStyle {
  overflow: visible !important;
}
.dialogList {
  // border-bottom: 1px solid #DCDFE6;
  height: calc(100%);
  ::v-deep >div{
    height: 100%;
    display: flex;
    flex-direction: column;
    .el-tabs{
      flex:1;
      // margin-bottom:4px;
      display: flex;
      flex-direction: column;
      .el-tabs__content{
        flex:1;
        .el-tab-pane{
          height: 100%;
          .div-height{
            height: 100% !important;
            .vif{
              height: 100%;
              .default_vue{
                height: 100% !important;
              }
            }
          }
        }
      }
    }
  }
}
</style>
